import { Button } from 'antd';
import { useState } from 'react';
import { useUserStore } from '@/stores';
import { useNavigate } from 'react-router';
import { useUserApi } from '@/apis';
import { TOKEN_STORAGE_KEY } from '@/common/constants';
import { tryApiRequest } from '@hdtd/utils';

const Login = () => {
  const [loading, setLoading] = useState(false);
  const userStore = useUserStore();
  const navigate = useNavigate();
  const userApi = useUserApi();

  const login = async () => {
    setLoading(true);
    const res = await tryApiRequest(() => userApi.login({ userName: '张三', password: '123' }));
    if (res?.code === API_RESULT_SUCCEED_CODE) {
      userStore.setState({ accessToken: res.data.token });
      sessionStorage.setItem(TOKEN_STORAGE_KEY, res.data.token);
      navigate('/');
    }
    setLoading(false);
  };
  return (
    <div>
      <Button loading={loading} onClick={login}>
        登录
      </Button>
    </div>
  );
};

export default Login;
